package com.snakerflow.framework.security.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.snakerflow.framework.security.entity.Position;
import com.snakerflow.framework.security.entity.User;

/**
 * shiro工具类
 * @author yuqs
 * @since 0.1
 */
public class ShiroUtils {
	private static final Logger log = LoggerFactory.getLogger(ShiroUtils.class);
	/**
	 * 返回当前登录的认证实体ID
	 * @return
	 */
	public static Long getUserId() {
		User user = getUser();
		if(user != null ) return user.getId();
		return -1L;
	}
	
	public static User getUser() {
		ShiroPrincipal principal = getPrincipal();
		if(principal != null) return principal.getUser();
		return null;
	}
	
	/**
	 * 返回当前登录的认证实体部门ID
	 * @return
	 */
	public static Long getOrgId() {
		User user = getUser();
		if(user != null && user.getOrg() != null) return user.getOrg().getId();
		return -1L;
	}
	
	/**
	 * 获取当前登录的认证实体
	 * @return
	 */
	public static ShiroPrincipal getPrincipal() {
		Subject subject = SecurityUtils.getSubject();
		return (ShiroPrincipal)subject.getPrincipal();
	}
	
	/**
	 * 获取所有组集合
	 * @return
	 */
	public static List<String> getGroups() {
		List<String> groups = new ArrayList<String>();
		ShiroPrincipal principal = getPrincipal();
		if(principal != null) {
			groups.addAll(principal.getRoles());
		}
		groups.add(String.valueOf(getUserId()));
		
		Long orgId = getOrgId();
		String posCode = getPosCode();
		/*if(orgId != null) {
			groups.add(String.valueOf(orgId));
		}
		if(posCode != null && !"".equals(posCode)){
			groups.add(posCode);
		}*/
		groups.add(posCode+"_"+orgId);
		groups.add(posCode);
		log.info(groups.toString());
		return groups;
	}
	
	/**
	 * 获取当前认证实体的中文名称
	 * @return
	 */
	public static String getFullname() {
		ShiroPrincipal principal = getPrincipal();
		if(principal != null) return principal.toString();
		return "";
	}
	
	/**
	 * 获取当前认证实体的登录名称
	 * @return
	 */
	public static String getUsername() {
		ShiroPrincipal principal = getPrincipal();
		if(principal != null) return principal.getUsername();
		throw new RuntimeException("user's name is null.");
	}
	
	/**
	 * 获取当前认证的实体部门名称
	 * @return
	 */
	public static String getOrgName() {
		User user = getUser();
		if(user != null) return user.getOrg().getName();
		return "";
	}
	
	//2015-12-17
	/**
	 * 返回当前登录的认证实体岗位ID
	 * @return
	 */
	public static String getPosCode() {
		User user = getUser();
		if(user != null && user.getPos() != null) {
			return user.getPos().getCode();
		}
		return "";
	}
	
	/**
	 * 返回当前登录的认证实体岗位上一级ID
	 * @return
	 */
	public static String getParentPosCode() {
		User user = getUser();
		if(user != null && user.getPos() != null) {
			Position parentPos = user.getPos();
			if(parentPos != null && parentPos.getParentPos() != null){
				return parentPos.getParentPos().getCode();
			}
		}
		return "";
	}
}
